package com.lf.freezingpoint.common.security.handler;

import com.alibaba.fastjson2.JSONObject;
import com.lf.freezingpoint.common.entity.R;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.logging.Logger;

/**
 * 自定义JWT认证异常,处理还未认证过的用户访问无权限资源时的异常
 */
@Component
public class JWTAuthenticationEntryPoint implements AuthenticationEntryPoint {
    private static final Logger logger = Logger.getLogger(JWTAuthenticationEntryPoint.class.toString());

    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException {
        response.setCharacterEncoding("utf-8");
        response.setContentType("json/javascript;charset=utf-8");
        if ("Full authentication is required to access this resource".equals(authException.getMessage())) {
            response.getWriter().print(JSONObject.toJSONString(R.fail("访问此资源需要完成身份验证")));
        } else {
            response.getWriter().print(JSONObject.toJSONString(R.fail(authException.getMessage())));
        }
        logger.info("JWTAuthenticationEntryPoint 异常处理");
    }
}
